import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style

NProgress.configure({ showSpinner: false })// NProgress Configuration

const whiteList = ['/login']; // no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start(); // start progress bar
  if (to.path === '/login') {
    if (!store.getters.token) {
      next();
      return;
    }
    next({ path: '/' })
  } else {
    /* 下面信息暂时改变，方便开发*/
    if (!store.getters.token) {
      next({ path: '/login', replace: true })
    } else {
      next()
    }
    if (!store.getters.permission_routers) { // 判断当前用户是否已拉取完user_info信息   store.getters.roles.length !== 0
      store.dispatch('generateRoutes', {}).then(() => { // 根据roles权限生成可访问的路由表
        router.addRoutes(store.getters.addRouters); // 动态添加可访问路由表
        next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
      })
    } else {
      if (to.name) {
        const matchViews = to.matched;
        for (let i = 1; i < matchViews.length; i++) {
          const toComponent = matchViews[i];
          if (typeof toComponent.components.default === 'function') {
            toComponent.components.default().then(item => {
              item.default.name = toComponent.name;
            });
          } else {
            toComponent.components.default && (toComponent.components.default.name = toComponent.name);
          }
        }
      }
    }
  }
});

router.afterEach(() => {
  NProgress.done() // finish progress bar
});
